package cz.spock.cms.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import cz.spock.cms.service.TemplateSourceService;
import cz.spock.cms.template.entity.TemplateSource;
import cz.spock.core.controller.BaseController;

/**
 * serves freemarker template related requests
 * 
 * TODO error handling
 * 
 * TODO SUBTEMPLATING
 * 
 * @author miso
 *
 */
@Controller
public class TemplateController extends BaseController {

    @Autowired
    private TemplateSourceService tService;
    
    // get all templates
    @RequestMapping(value = "/cms/templates", method = RequestMethod.GET)
    public ModelAndView templates(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("/cms/templates");
        List<TemplateSource> tl = tService.getAllTemplateSources();
        return new ModelAndView("cms/template/templates", "templates", tl);
    }
    
    @RequestMapping(value = "/cms/template/{id}", method = RequestMethod.GET)
    public ModelAndView template(@PathVariable Long id, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("/cms/template/" + id);
        TemplateSource ts = tService.getTemplateSourceById(id);
        return new ModelAndView("cms/template/template").addObject("template", ts);
    }
    
    @RequestMapping(value = "/cms/template/create", method = RequestMethod.GET)
    public ModelAndView templateCreateGet(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("/cms/template/create get");
        return new ModelAndView("cms/template/create");
    }
    
    @RequestMapping(value = "/cms/template/create", method = RequestMethod.POST)
    public String templateCreatePost(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("/cms/template/create post");
        // create template
        try {
            tService.createTemplateSource(request.getParameter("name"),
                    request.getParameter("description"),
                    request.getParameter("template"));
        } catch(Exception e) {            
            sendJson(response, tService.errorToJson(e.getMessage(), 0));
            return null;
//            return;
        }
        return "redirect:/cms/templates";
    }    

}
